package com.cnunicom.modules.tra.task;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.cnunicom.common.utils.DateUtils;
import com.cnunicom.modules.job.task.ITask;
import com.cnunicom.modules.tra.entity.MemberEntity;
import com.cnunicom.modules.tra.service.MemberService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;

/**
 * @Author: dingziyuan
 * @Date: 2020/3/23/023 21:54
 * @Description: 短信
 */
@Component("AliSmsTask")
public class AliSmsTask implements ITask {

    @Resource
    private DefaultAcsClient defaultAcsClient;

    @Resource
    private MemberService memberService;

    @Override
    public void run(String params) {

/*
        String[] split = DateUtils.getDate().split("-");
        String date = split[1] + split[2];

        // 通过当前日期查询身份证出生日期生日的人，发送短信
        final List<MemberEntity> list = memberService.query().select("mobile_num", "name")
                .eq("substr(id_card,11,4)", date)
                .list();*/

        String date = DateUtils.getDate();
        List<MemberEntity> list = memberService.query().select("mobile_num", "name")
                .eq("birthday", date)
                .list();
        list.forEach(mebEntity -> {
            try {
                final CommonRequest request = getRequest(mebEntity);
                final CommonResponse response = defaultAcsClient.getCommonResponse(request);
                System.out.println(response.getData());
            } catch (ClientException e) {
                e.printStackTrace();
            }
        });
    }


    private CommonRequest getRequest(MemberEntity memberEntity) {

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", memberEntity.getMobileNum());
        request.putQueryParameter("SignName", "运城市宾馆");
        request.putQueryParameter("TemplateCode", "SMS_186576837");
        final HashMap<String, String> map = new HashMap<>();
        map.put("mebName", memberEntity.getName());
        request.putQueryParameter("TemplateParam", JSON.toJSONString(map));

        return request;
    }
}
